package com.howbuy.tms.zuul.fallback;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.route.ZuulFallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 自定义Zuul回退机制处理器。
 * 路由熔断
 * 当zuul进行路由分发时，如果后端服务没有启动，或者调用超时，Zuul提供一种降级功能，而不直接将异常暴露出来。
 * (Zuul 目前只支持服务级别的熔断，不支持具体到某个URL进行熔断。)
 */
@Component
public class TmsOrderCenterFallback implements ZuulFallbackProvider {
    private final Logger logger = LoggerFactory.getLogger(ZuulFallbackProvider.class);

    //指定要处理的 service
    @Override
    public String getRoute() {
        //return "tms-order-center";//api服务id，如果需要所有调用都支持回退，则return "*"或return null
        return "*";
    }

    public ClientHttpResponse fallbackResponse() {
        return new ClientHttpResponse() {
            /**
             * 网关向api服务请求是失败了，但是消费者客户端向网关发起的请求是OK的，
             * 不应该把api的404,500等问题抛给客户端
             * 网关和api服务集群对于客户端来说是黑盒子
             */
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }
 
            @Override
            public int getRawStatusCode() throws IOException {
                return HttpStatus.OK.value();
            }
 
            @Override
            public String getStatusText() throws IOException {
                return HttpStatus.OK.getReasonPhrase();
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                JSONObject r = new JSONObject();
                try {
                    r.put("state", "9999");
                    r.put("msg", "系统错误，请求失败");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                logger.info("++++++service: {}", getRoute() + " service is unavailable.");
                return new ByteArrayInputStream(r.toString().getBytes("UTF-8"));
                //return new ByteArrayInputStream("The service is unavailable.".getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
                return headers;
            }
        };
    }
}

